<template>
  <div>
    <div class="wrapper" ref="wrapper">
      <div class="address">
        <h2 v-if="sectionType === 'regular' || sectionType === 'personal'">
          <span style="cursor: pointer;" @click="openNextPath({id: moduleId, sectionLevel: 0}, false)">{{title}}</span>
          <span v-if="currentLevel > 0" style="color: #999">/</span>
          <span style="cursor: pointer;" v-if="currentLevel > 0" @click="openNextPath({id: sectionPathId, sectionLevel: 1, sectionName: sectionPathName}, false)">{{sectionPathName}}</span>
          <span v-if="currentLevel > 1 && sectionType === 'regular'" style="color: #999">/</span>
          <span v-if="currentLevel > 1 && sectionType === 'regular'">{{projectPathName}}</span>
        </h2>
        <hr v-if="sectionType === 'regular' || sectionType === 'personal'">
        <div v-if="currentLevel < 2">
          <div class="folder-item" v-for="item in pathArr" :key="item.id" @click="openNextPath(item)">
            <img v-if="item.sectionLevel === 1" src="../../assets/img/lanmu.png" alt="">
            <img v-if="item.sectionLevel === 2 || sectionType === 'personal'" src="../../assets/img/project.png" alt="">
            {{item.sectionName}}
          </div>
        </div>
         <div v-if="(!showArticle && currentLevel === 2) || (sectionType !== 'regular' && sectionType !== 'personal')" class="article-wrapper">
          <div class="data-wrapper">
            <div v-if="sectionType === 'regular' || sectionType === 'home'" class="search-bar clearfix">
              <el-dropdown :show-timeout="0" @command="selectTime">
                <span class="el-dropdown-link" >
                  {{timeName? timeName: '更新时间'}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="day3">最近三天</el-dropdown-item>
                  <el-dropdown-item command="day7">最近一周</el-dropdown-item>
                  <el-dropdown-item command="day30">最近一个月</el-dropdown-item>
                  <el-dropdown-item command="">全部</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <span style="margin-left:10px; cursor:pointer; color: #336699;" @click="searchItem(true)">刷新<i class="el-icon-refresh"></i></span>
              <div class="search-btn" v-if="sectionType === 'home'">
                <el-input placeholder="搜索" @change="searchItem(true)" v-model="searchKey" :clearable="true" suffix-icon="el-icon-search"></el-input>
              </div>
            </div>
            <div v-if="sectionType === 'regular' || sectionType === 'home'" class="data-header">
              <div :style="{'width': isManage? '50%': '60%'}">文章标题</div>
              <div style="width: 10%;min-width: 100px;">作者</div>
              <div style="width: 15%;min-width: 150px;">更新时间</div>
              <div style="width: 15%;min-width: 100px;">收藏/点赞/转发</div>
              <div v-if="isManage" style="width: 10%;min-width: 50px;">操作</div>
            </div>
            <div v-if="sectionType === 'regular' || sectionType === 'home'" ref="scrollcontainer" class="data-list" :style="{'height': sectionType === 'home' ? 'calc(100vh - 320px)': 'calc(100vh - 390px)'}">
              <ArticleList @editArticle="editArticle" @share="share" @managerDel="managerDel" :isHot="page === 1 && sectionType === 'home' && idx < 3" @openArticle="openArticle(item.id)" v-for="(item, idx) in articleList" :key="item.id" :isMg="isManage" :articleDesc="item"/>
              <div class="empty-tr" v-if="articleList.length === 0">暂无数据</div>
            </div>
            <div v-if="sectionType === 'collection'" class="data-header">
              <div style="width: 60%;">文章标题</div>
              <div style="width: 10%;min-width: 100px;">作者</div>
              <div style="width: 15%;min-width: 150px;">收藏时间</div>
              <div style="width: 15%;min-width: 100px;">操作</div>
            </div>
            <div v-if="sectionType === 'collection'" ref="scrollcontainer" class="data-list" style="height: calc(100vh - 270px);">
              <ArticleList :showOperator="false" :isCollection="true" @cancelCollect="cancelCollect(item.contextId)" @openArticle="openArticle(item.contextId)" v-for="item in articleList" :key="item.id" :articleDesc="item"/>
              <div class="empty-tr" v-if="articleList.length === 0">暂无数据</div>
            </div>
            <div v-if="sectionType === 'personal'" class="data-header">
              <div style="width: 60%;min-width: 150px;">文章标题</div>
              <div style="width: 15%;min-width: 150px;">更新时间</div>
              <div style="width: 15%;min-width: 150px;">更新时间</div>
              <div style="width: 10%;min-width: 100px;">操作</div>
            </div>
            <div v-if="sectionType === 'personal'" ref="scrollcontainer" class="data-list" style="height: calc(100vh - 340px);">
              <ArticleList @managerDel="managerDel" @openArticle="openArticle(item.id)" @delArticle="delArticle" @rebackArticle="rebackArticle" @editArticle="editArticle" :showOperator="true" v-for="item in articleList" :key="item.id" :articleDesc="item"/>
              <div class="empty-tr" v-if="articleList.length === 0">暂无数据</div>
            </div>
          </div>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="page"
            :page-sizes="[10, 15, 20, 50]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>
      </div>
      <div v-if="showArticle" class="article-class">
        <Article @share="share" :isMg="isManage" @scrolltopemit="scrollTop" :articleId="currentArticleId" @close="closeArticle"/>
      </div>
      <div v-if="!showArticle" class="create-btn">
        <el-button style="width: 50px; height: 50px;" type="primary" icon="el-icon-edit" @click="createArticle" circle></el-button>
      </div>
      <Editor v-if="showEditor" :articleId="currentArticleId" @close="closeEditor" />
    </div>
  </div>
</template>

<script>
import ArticleList from '@/components/bbs/ArticleList'
import Article from '@/components/bbs/Article'
import {dateUtil} from '@/utils/dateUtil'
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import Editor from '@/components/bbs/Editor'

export default {
  data () {
    return {
      showArticle: false,
      articleList: [],
      searchKey: '',
      currentArticleId: '',
      pageSize: 10,
      page:1,
      totalPage: 0,
      currentSectionId: '',
      sectionList: [],
      timeName: '',
      articleStartTime: '',
      articleEndtime: '',
      showEditor: false,
      isModuleManager: false,
      isSectionManager: false,
      isProjectManager: false,
      defaultProps: {
        children: 'children',
        label: 'sectionName',
        isLeaf: 'leaf'
      },
      pathArr: [],
      currentLevel: 0,
      sectionPathName: '',
      sectionPathId: '',
      projectPathName: '',
      projectPathId: ''
    }
  },
  mixins: [dingMixin],
  props: ['moduleId', 'sectionType', 'title'],
  components: {
    ArticleList,
    Article,
    Editor
  },
  computed: {
    isManage() {
      return this.isModuleManager || this.isSectionManager || this.isProjectManager || (this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1250299091356758017'))
    }
  },
  methods: {
    closeArticle() {
      this.showArticle = false;
      this.searchItem()
    },
    closeEditor() {
      this.showEditor = false;
      this.searchItem()
    },
    openArticle(id) {
      this.currentArticleId = id;
      if(this.sectionType === 'personal') {
        this.showEditor = true;
      }else{
        this.showArticle = true;
      }
    },
    share(id, title) {
      this.complexPicker(1).then(async (data) => {
        if(!await this.$httpN.postB('community/article/share', {
          usernames: '@' + data[0].name,
          content: title,
          url: id
        })) return;
        formUtil.submitSuccess('分享成功');
      })
    },
    scrollTop() {
      this.$refs.wrapper.scrollTop = 0;
    },
    editArticle(id) {
      this.currentArticleId = id;
      this.showEditor = true;
    },
    rebackArticle(id) {
      formUtil.submitConfirm('此操作将恢复文章到草稿箱, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/recycle', {ids: id, articleStatus: 0})) return;
        formUtil.submitSuccess('恢复成功');
        this.searchItem()
      })
    },
    delArticle(id) {
      formUtil.submitConfirm('此操作将删除文章到回收站, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/recycle', {ids: id, articleStatus: 2})) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem()
      })
    },
    managerDel(id) {
      formUtil.submitConfirm('此操作将永久删除该文章, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/article/delete', {ids: id})) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem()
      })
    },
    createArticle() {
      this.currentArticleId = '';
      this.showEditor = true;
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data;
      if(this.sectionType === 'regular' || this.sectionType === 'home'){
        if(this.sectionType === 'regular' && this.currentSectionId === '') return;
        if(this.searchKey) {
          data = await this.$httpN.postB('community/article/search', {
            page: this.page,
            limit: this.pageSize,
            sectionId: this.sectionType === 'home' ? '' :this.moduleId,
            isHomeSearch: this.sectionType === 'home' ? '1' :'',
            articleSearch: this.searchKey,
            articleStatus: 1
          })
        }else {
          data = await this.$httpN.postB('community/article/list', {
            page: this.page,
            limit: this.pageSize,
            sectionId: this.currentSectionId,
            articleStartTime: this.articleStartTime,
            articleEndtime: this.articleEndtime,
            isHomeSearch: this.sectionType === 'home' ? '1' :'',
            articleStatus: 1
          })
        }
      }else if(this.sectionType === 'collection') {
        data = await this.$httpN.postB('community/likecollection/list', {
          page: this.page,
          limit: this.pageSize,
          userId: this.userInfo.dingId,
          dataType: 1
        })
      }else if(this.sectionType === 'personal') {
        data = await this.$httpN.postB('community/article/userList', {
          page: this.page,
          limit: this.pageSize,
          sectionId: this.currentSectionId === '-99' || this.currentSectionId === '-98'? '': this.currentSectionId,
          articleStatus: this.currentSectionId === '-99'? '2': this.currentSectionId === '-98'? '0': '1'
        })
      }
      this.$refs.scrollcontainer.scrollTop = 0;
      this.articleList = data.list;
      this.totalPage = data.totalCount;
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.searchItem(true);
    },
    currentChangeHandle(page) {
      this.page = page;
      this.searchItem();
    },
    changeSection(id, section) {
      this.currentSectionId = id;
      this.searchItem(true);
    },
    async cancelCollect(id) {
      if(!await this.$httpN.postB('community/likecollection/like', {
        userId: this.userInfo.dingId,
        contextId: id,
        dataType: 1,
        status: 0
      })) return
      formUtil.submitSuccess('取消收藏成功');
      await this.searchItem(true);
    },
    selectTime(e) {
      this.articleEndtime = dateUtil.thisDay() + ' 23:59:59';
      if(e === 'day3') {
        this.timeName = '最近三天';
        this.articleStartTime = dateUtil.nDaysBefore(3);
      }else if(e === 'day7'){
        this.timeName = '最近一周';
        this.articleStartTime = dateUtil.nDaysBefore(7);
      }else if(e === 'day30'){
        this.timeName = '最近一个月';
        this.articleStartTime = dateUtil.nDaysBefore(30);
      }else {
        this.timeName = '全部';
        this.articleEndtime = '';
        this.articleStartTime = '';
      }
      this.searchItem(true)
    },
    async openNextPath(item, checkManager) {
      if(this.sectionType === 'personal') {
        if(checkManager === false && item.sectionLevel === 0) {
          this.currentLevel = 0;
          this.pathArr = formUtil.deepCopy(this.sectionList);
          return 
        }
        this.sectionPathName = item.sectionName;
        this.sectionPathId = item.id;
        this.currentLevel = 2;
        this.changeSection(item.id, item)
        return
      }

      this.currentLevel = item.sectionLevel;
      if(item.sectionLevel === 1) {
        this.sectionPathName = item.sectionName;
        this.sectionPathId = item.id;
        if(checkManager){
          let managerArr = item.sectionManageUserid.split(',');
          this.isSectionManager = managerArr.includes(this.userInfo.dingId);
        }
        let data = await this.$httpN.postQ('community/section/list', {'parentid': item.id})
        if(data.length > 0) {
          data = data.filter((item) => {
            if(item.sectionUserid !== '') {
              let managerArr = item.sectionManageUserid.split(',');
              let userArr = item.sectionUserid.split(',');
              if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || this.isModuleManager || this.isSectionManager) {
                return true;
              }else {
                return userArr.includes(this.userInfo.dingId);
              }
            }else{
              return true;
            }
          })
        }
        this.pathArr = data;
      }else if(item.sectionLevel === 2) {
        if(checkManager){
          let managerArr = item.sectionManageUserid.split(',');
          this.isProjectManager = managerArr.includes(this.userInfo.dingId);
        }
        this.projectPathName = item.sectionName;
        this.projectPathId = item.id;
        this.changeSection(item.id, item)
      }else if(item.sectionLevel === 0) {
        let data = await this.$httpN.postQ('community/section/list', {'parentid': item.id})
        if(data.length > 0) {
          data = data.filter((item) => {
            if(item.sectionUserid !== '') {
              let managerArr = item.sectionManageUserid.split(',');
              let userArr = item.sectionUserid.split(',');
              if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || this.isModuleManager) {
                return true;
              }else {
                return userArr.includes(this.userInfo.dingId);
              }
            }else{
              return true;
            }
          })
        }
        this.pathArr = data;
      }
    }
  },
  async mounted() {
    this.$refs.wrapper.style.height = document.documentElement['clientHeight'] - 162 + 'px';
    window.onresize = () => {
      this.$refs.wrapper.style.height = document.documentElement['clientHeight'] - 162 + 'px';
    }
    if(this.sectionType === 'regular'){
      let modules = await this.$httpN.postQ('community/section/list', {'parentid': null});
      modules.forEach((moduleItem) => {
        if(moduleItem.id === this.moduleId){
          let managerArr = moduleItem.sectionManageUserid.split(',');
          this.isModuleManager = managerArr.includes(this.userInfo.dingId);
        }
      })
    }
    if(this.sectionType === 'personal') {
      this.sectionList = await this.$httpN.postQ('community/section/list', {'parentid': null})
      this.sectionList.push({sectionName: '草稿箱', id: '-98'})
      this.sectionList.push({sectionName: '回收站', id: '-99'})
      this.pathArr = formUtil.deepCopy(this.sectionList);
    }
    if(this.sectionType !== 'regular' && this.sectionType !== 'personal'){
      await this.searchItem(true);
    }
    if(this.sectionType === 'home') {
      let articleId = this.$route.params.id;
      if(articleId) this.openArticle(articleId);
    }
    if(this.sectionType === 'regular') {
      let data = await this.$httpN.postQ('community/section/list', {'parentid': this.moduleId})
      if(data.length > 0) {
        data = data.filter((item) => {
          if(item.sectionUserid !== '') {
            let managerArr = item.sectionManageUserid.split(',');
            let userArr = item.sectionUserid.split(',');
            if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || this.isModuleManager) {
              return true;
            }else {
              return userArr.includes(this.userInfo.dingId);
            }
          }else{
            return true;
          }
        })
      }
      this.pathArr = data;
    }
  }
}
</script>

<style lang="scss" scoped>
  .create-btn{
    position: fixed;
    bottom: 70px;
    right: 50px;
  }
  .wrapper{
    width: 100%;
    display: flex;
    height: 100%;
    position: relative;
    overflow-y: auto;
    .module-bar{
      padding-top: 50px;
      text-align: center;
      max-width: 200px;
      min-width: 150px;
      width: 12.5%;
      border-right: 1px solid #e8e8e8;
      height: 100%;
      padding-right: 20px;
      div{
        line-height: 50px;
        font-size: 16px;
        cursor: pointer;
        color:#595959;
        font-weight: bold;
        &.active{
          color: #409EFF;
        }
      }
    }
    .article-wrapper{
      flex: 1;
      // padding-left: 20px;
    }
    .tree-wrapper{
      padding-left: 20px;
      .el-tree{
        color: #595959;
      }
    }
    .address{
      flex: 1;
      .folder-item{
        line-height: 70px;
        border:1px solid #515151;
        margin-top: 20px;
        padding-left: 20px;
        position: relative;
        cursor: pointer;
        img{
          width: 50px;
          margin-right: 20px;
        }
      }
    }
  }
  .data-wrapper{
    margin-top: 10px;
    border: 1px solid #e8e8e8;
    border-bottom: none;
    .search-bar{
      height: 52px;
      line-height: 52px;
      background: rgba(0,0,0,0);
      border-bottom: 1px solid #e8e8e8;
      border-radius: 2px 2px 0 0;
      padding: 0 16px;
      .search-btn{
        float:right;
      }
    }
    .data-list{
      overflow: auto;
      border-bottom: 1px solid #e8e8e8;
    }
  }
  .data-header{
    height: 48px;
    line-height: 48px;
    padding: 0 20px;
    background: #f1f4f5;
    font-size: 0;
    display:flex;
    min-width: 700px;
    div{
      display:inline-block;
      font-size: 14px;
      color: #8c8c8c;
    }
  }
  .el-dropdown-link {
    cursor: pointer;
    color: rgb(51, 102, 153);
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }

  .article-class{
    position: absolute;
    top:0;
    right:0;
    min-height: 100%;
    width: 100%;
    z-index: 2;
    background: white;;
  }
  .empty-tr{
    line-height: 48px;
    text-align: center;
    cursor: pointer;
    border-bottom: 1px solid #e8e8e8;
    &:hover{
      background: #fafafa;
    }
  }

  .article-class{
    position: absolute;
    top:0;
    right:0;
    min-height: 100%;
    width: 100%;
    z-index: 2;
    background: white;;
  }
</style>